<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
// 注意：保持 coupon.js 不变，使用它导出的 getCouponsByStatus
import { getCouponsByStatus } from "../api/coupon.js";
// 领取接口应从 usercoupon.js 引入（你的后端领取接口在 /app/usercoupon）
import { receiveCoupon as apiReceiveCoupon } from "../api/userCoupon.js";

const router = useRouter();
const couponList = ref([]);
const currentFilter = ref("all");

// 获取用户ID的辅助函数（用于调用后端 /userId/{userId}/status/1）
const getUserId = () => {
  return localStorage.getItem("userId");
};

onMounted(() => {
  fetchCoupons();
});

// 根据后端返回结构映射并设置是否已领取
async function fetchCoupons() {
  try {
    const userId = getUserId() || 11; // 如果本地没 userId，临时用 11 方便测试（你的示例是 11）
    console.log("📌 请求可领取优惠券，userId=", userId);
    const response = await getCouponsByStatus(userId, 1); // 你现在的 coupon.js 写死 status=1，这里仍传 1
    console.log("✅ 优惠券列表响应:", response);

    // 后端示例结构： { code:200, message:"查询成功", data: [ { coupon: {...}, userCoupon: {...} }, ... ] }
    if (
      response.data &&
      response.data.code === 200 &&
      Array.isArray(response.data.data)
    ) {
      couponList.value = response.data.data.map((item) => {
        const c = item.coupon || {};
        const uc = item.userCoupon || {};

        // 判断是否已领取：如果 userCoupon.userId 或 userCoupon.userCouponId 存在且非 null，就认为已领取
        const isReceived = !!(uc.userId || uc.userCouponId);

        return {
          id: c.couponId,
          name: c.couponName,
          amount: c.couponValue,
          desc: c.couponType || "",
          startTime: c.startTime,
          endTime: c.endTime,
          createTime: c.createTime,
          updateTime: c.updateTime,
          isReceived,
          // 判断是否过期（简单判断：endTime < today）
          isExpired: c.endTime ? new Date(c.endTime) < new Date() : false,
          _raw: item,
        };
      });
      console.log("🎯 映射后的优惠券列表:", couponList.value);
    } else {
      console.error("❌ 获取优惠券失败或返回数据格式不对:", response.data);
    }
  } catch (error) {
    console.error("❌ 获取优惠券接口异常:", error);
  }
}

// 领取优惠券
async function receiveCoupon(coupon) {
  const userId = getUserId();
  if (!userId) {
    alert("请先登录");
    router.push("/login");
    return;
  }

  const userCouponParam = {
    userId: Number(userId),
    couponId: coupon.id,
  };

  try {
    console.log("👉 发送领取请求:", userCouponParam);
    const response = await apiReceiveCoupon(userCouponParam);
    console.log("✅ 领取返回:", response.data);

    if (response.data.code === 200) {
      alert("领取成功 ✅");
      fetchCoupons(); // 🔥 领取完自动刷新界面
    } else {
      alert(response.data.message || "领取失败");
    }
  } catch (error) {
    console.error("❌ 领取异常:", error);
    alert(error.response?.data?.message || "领取失败");
  }
}

// 过滤后的优惠券 - 维持和你的 template 配合的结构
const filteredCoupons = computed(() => {
  if (currentFilter.value === "all") {
    return {
      valid: couponList.value.filter(
        (coupon) => !coupon.isExpired && !coupon.isReceived
      ),
      expired: couponList.value.filter((coupon) => coupon.isExpired),
      all: couponList.value,
    };
  }

  if (currentFilter.value === "valid") {
    return {
      valid: couponList.value.filter(
        (coupon) => !coupon.isExpired && !coupon.isReceived
      ),
      expired: [],
      all: couponList.value.filter(
        (coupon) => !coupon.isExpired && !coupon.isReceived
      ),
    };
  }

  if (currentFilter.value === "expired") {
    return {
      valid: [],
      expired: couponList.value.filter((coupon) => coupon.isExpired),
      all: couponList.value.filter((coupon) => coupon.isExpired),
    };
  }

  return {
    valid: couponList.value,
    expired: [],
    all: couponList.value,
  };
});

// 跳转到我的优惠券页面
const goToMyCoupon = () => {
  const userId = getUserId();
  if (!userId) {
    alert("请先登录");
    router.push("/login");
    return;
  }

  router.push({
    path: "/mycouponList",
    query: { userId: userId },
  });
};
</script>

<template>
  <div class="coupon-container">
    <div class="header">
      <div class="title">平台优惠券</div>

      <button class="my-coupon-btn" @click="goToMyCoupon">我的优惠券</button>
    </div>

    <div class="coupon-list">
      <!-- 有效优惠券 -->
      <div v-if="filteredCoupons.valid.length > 0">
        <div class="section-title">
          可使用 ({{ filteredCoupons.valid.length }})
        </div>
        <div class="coupon-cards">
          <div
            class="coupon-card valid"
            v-for="coupon in filteredCoupons.valid"
            :key="coupon.id"
          >
            <div class="coupon-left">
              <div class="amount">¥{{ coupon.amount }}</div>
            </div>
            <div class="coupon-right">
              <div class="name">{{ coupon.name }}</div>
              <div class="desc">{{ coupon.desc }}</div>
              <div class="date">有效期至 {{ coupon.endTime }}</div>
              <button
                class="use-btn receive-btn"
                @click="receiveCoupon(coupon)"
                :disabled="coupon.isReceived"
              >
                {{ coupon.isReceived ? "已领取" : "立即领取" }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div
        class="empty-state"
        v-if="filteredCoupons.valid.length === 0 && couponList.length > 0"
      >
        <p>暂无可用优惠券</p>
      </div>

      <div class="empty-state" v-if="couponList.length === 0">
        <img
          src="https://img01.51jobcdn.com/im/images/2023/coupon/empty.png"
          alt="暂无优惠券"
          class="empty-img"
        />
        <p>暂无优惠券</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 容器样式 */
.coupon-container {
  width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f6;
  min-height: calc(100vh - 60px);
}

/* 头部样式 */
.header {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.sub-title {
  color: #666;
  font-size: 13px;
  margin-bottom: 15px;
  margin-right: 20px;
}

.my-coupon-btn {
  padding: 8px 15px;
  background-color: #a2131d;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  margin-bottom: 15px;
}

/* 筛选标签样式 */
.filter-tabs {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.filter-tabs button {
  padding: 8px 20px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-tabs button.active {
  background-color: #a2131d;
  color: #fff;
  border-color: #a2131d;
}

.filter-tabs button:hover:not(.active) {
  border-color: #a2131d;
  color: #a2131d;
}

/* 优惠券列表样式 */
.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
}

.coupon-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 15px;
}

/* 优惠券卡片样式 */
.coupon-card {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.coupon-card:hover {
  transform: translateY(-3px);
}

.coupon-card.valid {
  border: 1px solid #a2131d;
}

.coupon-card.expired {
  border: 1px solid #ddd;
  opacity: 0.7;
}

/* 卡片左侧金额区域 */
.coupon-left {
  flex: 1;
  padding: 20px;
  text-align: center;
  background-color: #fdf2f2;
  position: relative;
}

.coupon-card.valid .coupon-left {
  background-color: #fdf2f2;
}

.coupon-card.expired .coupon-left {
  background-color: #f5f5f5;
}

.amount {
  font-size: 28px;
  font-weight: 700;
  color: #a2131d;
  line-height: 3.5;
  margin-bottom: 5px;
}

.condition {
  font-size: 12px;
  color: #666;
}

/* 卡片右侧信息区域 */
.coupon-right {
  flex: 2;
  padding: 15px 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
  line-height: 1.4;
}

.date {
  font-size: 12px;
  color: #999;
  margin-top: auto;
}

/* 使用按钮样式 */
.use-btn {
  align-self: flex-start;
  margin-top: 10px;
  padding: 6px 15px;
  background-color: #a2131d;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.use-btn:hover {
  background-color: #b4121d;
}

.receive-btn {
  background-color: #8a1018;
}

.receive-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 50px 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-top: 20px;
}

.empty-img {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  opacity: 0.7;
}

.empty-state p {
  color: #999;
  font-size: 16px;
  margin-bottom: 20px;
}

.get-more {
  padding: 8px 20px;
  background-color: #a2131d;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.get-more:hover {
  background-color: #8a1018;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .coupon-container {
    padding: 10px;
  }

  .coupon-cards {
    grid-template-columns: 1fr;
  }

  .coupon-card {
    flex-direction: column;
  }

  .coupon-left {
    padding: 15px;
  }

  .amount {
    font-size: 24px;
  }

  .filter-tabs {
    overflow-x: auto;
    padding-bottom: 5px;
  }

  .filter-tabs button {
    flex-shrink: 0;
  }
}
</style>
